package com.ytxg.health_management.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.ytxg.health_management.mapper.UserIpMapper;
import com.ytxg.health_management.pojo.dto.UserDto;
import com.ytxg.health_management.pojo.entity.Result;
import com.ytxg.health_management.pojo.entity.User;
import com.ytxg.health_management.pojo.entity.UserIp;
import com.ytxg.health_management.pojo.vo.UserRegister;
import com.ytxg.health_management.service.UserService;
import com.ytxg.health_management.util.JWTUtils;
import com.ytxg.health_management.util.MyException;
import com.ytxg.health_management.util.ResultCode;
import com.ytxg.health_management.webSocket.WebSocketServer;
import com.ytxg.health_management.webSocket.entity.WebSocketMessage;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserIpMapper userIpMapper;

    /**
     * 用户注册
     *
     * @param userRegister
     * @return Result
     */
    @PostMapping("/register")
    public Result<Map<String, Object>> register(@RequestBody UserRegister userRegister) {
        if (userRegister.getUserName() == null || userRegister.getUserName().equals("")) {
            return Result.fail("用户名不能为空");
        }
        String userName = userService.getUserName(userRegister.getUserName());
        if (userName != null && userName.equals(userRegister.getUserName())) {
            return Result.fail("用户名已存在");
        }

        try {
            int res = userService.register(userRegister);
            if (res == 1) {
                Result<Map<String, Object>> login = login(userRegister);
                return login;
            } else {
                return Result.fail("注册失败");
            }
        } catch (Exception e) {
            System.out.println(e);
            return Result.fail("注册失败");
        }
    }

    /**
     * 用户登录
     *
     * @param userRegister
     * @return
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody UserRegister userRegister) {
        if (userRegister.getUserName() == null || userRegister.getUserName().equals("")) {
            return Result.fail("用户名不能为空");
        }
        Result<Map<String, Object>> login = userService.login(userRegister);
        UserDto user = (UserDto)login.getData().get("user");
        WebSocketServer.sendMessageToAll(new WebSocketMessage<>()
                .setData("用户" + user.getNickName() + "登录了系统")
                .setType("string")
        );
        return login;
    }

    @PostMapping("/setIp")
    public Result<String> setIp(@RequestBody UserIp userIp, @RequestHeader("Authorization") String token) {
        Result<UserDto> userDtoResult = tokenAuth(token);
        userIp.setUserId(userDtoResult.getData().getId());
        userIp.setLoginTime(new Date());
        userIpMapper.addIp(userIp);
        return Result.success("设置成功",null);
    }

    /**
     * token验证
     *
     * @param token
     * @return
     */
    @GetMapping("/tokenAuth")
    public Result<UserDto> tokenAuth(@RequestHeader("Authorization") String token) {
        try {
            DecodedJWT verify = JWTUtils.verify(token);
            String username = verify.getClaim("username").asString();
            UserDto userInfo = userService.getUserInfo(username);
            return Result.success(userInfo);
        } catch (Exception e) {
            throw new MyException(ResultCode.USER_AUTH_FALL, "当前用户登录信息已过期,请刷新或者重新登陆");
        }
    }

    /**
     * 修改密码
     *
     */
    @PostMapping("/updatePsw")
    public Result<String> updatePsw(@RequestHeader("Authorization") String token, @RequestBody User user) {
        Result<UserDto> auth = tokenAuth(token);
        if (auth.getCode() == ResultCode.USER_AUTH_FALL) {
            return Result.fail("当前用户登录信息已过期");
        }
        Result<String> res = userService.updatePsw(auth.getData().getUserName(), user);
        return res;
    }

    @PostMapping("/getAll")
    public Result<Map<String,Object>> getAll(@RequestBody User user) {
        return userService.getAll(user);
    }

    @GetMapping("/updateImg")
    public Result<String> updateImg(@RequestParam("img") String img,@RequestHeader("Authorization") String token) {
        Result<UserDto> userDtoResult = tokenAuth(token);

        return userService.updateImg(img, userDtoResult.getData().getId());
    }

    @GetMapping("/authAdmin")
    public Result<Boolean> authAdmin(@RequestHeader("Authorization") String token) {
        Result<UserDto> userDtoResult = tokenAuth(token);
        if(userDtoResult.getData().getLevel()==1){
            return Result.success(true);
        }
        return Result.success(false);
    }

    @PostMapping("/updateUser")
    public Result<String> updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }
    @GetMapping("/deleteUser")
    public Result<String> deleteUser(@RequestParam("id") int id,@RequestHeader("Authorization") String token) {
        Result<UserDto> userDtoResult = tokenAuth(token);
        User user = new User();
        user.setId(id);
        return userService.deleteUser(user);
    }
}
